#!/usr/bin/env python3
"""
OCR API Demo Script
This script demonstrates how to use the OCR API service
"""

import sys
import subprocess
import time
import requests
import json
from pathlib import Path

def check_dependencies():
    """Check if required dependencies are installed"""
    try:
        import fastapi
        import uvicorn
        import paddleocr
        import cv2
        import numpy
        print("✓ All dependencies are installed")
        return True
    except ImportError as e:
        print(f"✗ Missing dependency: {e}")
        print("Please install dependencies using: pip install -r requirements.txt")
        return False

def start_server_demo():
    """Demo function to show how to start the server"""
    print("=" * 60)
    print("OCR API Server Demo")
    print("=" * 60)
    
    print("\n1. To start the server manually:")
    print("   python main.py")
    print("   or")
    print("   uvicorn main:app --host 0.0.0.0 --port 8000 --reload")
    
    print("\n2. To use the batch startup script:")
    print("   On Windows: start_server.bat")
    print("   On Linux/Mac: ./start_server.sh")
    
    print("\n3. API Endpoints will be available at:")
    print("   - Health check: http://localhost:8001/")
    print("   - API docs: http://localhost:8001/docs")
    print("   - OCR upload: http://localhost:8001/ocr/upload")
    print("   - OCR base64: http://localhost:8001/ocr/base64")
    print("   - Languages: http://localhost:8001/ocr/languages")

def show_usage_examples():
    """Show usage examples"""
    print("\n" + "=" * 60)
    print("Usage Examples")
    print("=" * 60)
    
    print("\n1. Python Client Example:")
    print("""
import requests
import base64

# Upload image file
with open('image.jpg', 'rb') as f:
    files = {'file': f}
    response = requests.post('http://localhost:8001/ocr/upload', files=files)
    result = response.json()
    print("Recognized text:", result['data']['total_text'])

# Base64 image processing
with open('image.jpg', 'rb') as f:
    image_data = base64.b64encode(f.read()).decode()
    response = requests.post('http://localhost:8001/ocr/base64', json=image_data)
    result = response.json()
    print("Recognized text:", result['data']['total_text'])
""")
    
    print("\n2. cURL Examples:")
    print("""
# Upload file
curl -X POST "http://localhost:8001/ocr/upload" \\
     -H "accept: application/json" \\
     -H "Content-Type: multipart/form-data" \\
     -F "file=@image.jpg"

# Health check
curl -X GET "http://localhost:8001/health"

# Get supported languages
curl -X GET "http://localhost:8001/ocr/languages"
""")

def show_project_structure():
    """Display project structure"""
    print("\n" + "=" * 60)
    print("Project Structure")
    print("=" * 60)
    
    structure = """
ocr/
├── main.py                 # FastAPI application entry point
├── requirements.txt        # Python dependencies
├── .env.example           # Environment variables template
├── start_server.bat       # Windows startup script
├── start_server.sh        # Linux/Mac startup script
├── test_api.py           # API testing script
├── demo.py               # This demo script
├── README.md             # Detailed documentation
├── config/
│   ├── __init__.py
│   └── settings.py        # Application settings
├── models/
│   ├── __init__.py
│   └── response_models.py # Pydantic response models
├── services/
│   ├── __init__.py
│   └── ocr_service.py     # OCR service implementation
└── utils/
    ├── __init__.py
    ├── file_utils.py      # File handling utilities
    └── logging_utils.py   # Logging configuration
"""
    print(structure)

def show_configuration():
    """Show configuration options"""
    print("\n" + "=" * 60)
    print("Configuration Options")
    print("=" * 60)
    
    print("Environment variables (create .env file):")
    config_vars = """
HOST=0.0.0.0                # Server host
PORT=8001                   # Server port
DEBUG=true                  # Debug mode
OCR_LANGUAGE=ch             # OCR language (ch=Chinese+English)
OCR_USE_ANGLE_CLS=true      # Enable angle classification
OCR_USE_SPACE_CHAR=true     # Use space character
OCR_GPU=false               # Use CPU version
MAX_FILE_SIZE=10485760      # Max file size (10MB)
LOG_LEVEL=INFO              # Logging level
"""
    print(config_vars)

def main():
    """Main demo function"""
    print("OCR Image Recognition API - Demo")
    print("Built with FastAPI + PaddleOCR 3.1 + PaddlePaddle 3.2.0 CPU")
    
    # Check if we're in the right directory
    if not Path("main.py").exists():
        print("Error: Please run this script from the OCR project directory")
        sys.exit(1)
    
    # Check dependencies
    deps_ok = check_dependencies()
    
    # Show demo information
    start_server_demo()
    show_usage_examples()
    show_project_structure()
    show_configuration()
    
    print("\n" + "=" * 60)
    print("Next Steps")
    print("=" * 60)
    
    if not deps_ok:
        print("1. Install dependencies:")
        print("   pip install -r requirements.txt")
        print()
    
    print("2. Start the server:")
    print("   python main.py")
    print()
    print("3. Test the API:")
    print("   python test_api.py")
    print()
    print("4. Open browser and visit:")
    print("   http://localhost:8001/docs")
    print()
    print("5. For detailed documentation, see README.md")
    
    print("\n" + "=" * 60)
    print("Demo completed! Your OCR API project is ready to use.")
    print("=" * 60)

if __name__ == "__main__":
    main()